﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using VNet.VisiSuite.Common;
using VNet.VisiSuite.Controls;
using VNet.VisiSuite.Service.Contact.Message.Item;
using VNet.VisiSuite.VisiBoard.Common.Helpers;
using VNet.VisiSuite.VisiBoard.Controls;
using VNet.VisiSuite.VisiBoard.Dal.EntityClasses;
using VNet.VisiSuite.VisiBoard.ViewModels;

namespace VNet.VisiSuite.VisiBoard.Views
{
    public partial class DowntimeDialogView : VisiDialog
    {
        private DowntimeDialogViewModel _model;
        private int _progress_bar_value;
        private System.Timers.Timer _timer;
        private bool _visibox_event;

        public EventHandler UpdateInputKeyboard;

        public DowntimeDialogView(bool is_process_visibox_event = false, bool is_break_lunch = false)
        {
            InitializeComponent();
            var menu_items = new List<VNetMenuItem>();
            menu_items.Add(new VNetMenuItem(null, "OK", CommonConstants.VNetIcon.AppbarCheck, VNetMenuItemType.WhiteBackgroundTheme, onOK));
            menu_items.Add(new VNetMenuItem(null, "Cancel", CommonConstants.VNetIcon.AppbarClose, VNetMenuItemType.WhiteBackgroundTheme, onCancel));
            _menu.Icons = menu_items;
            _menu.Icons[0].IsEnabled = false;
            _bottom_bar.Icons = new List<VNetMenuItem>
            {
                new VNetMenuItem(null, "Input Keyboard",CommonConstants.VNetIcon.AppbarInputKeyboard,VNetMenuItemType.WhiteBackgroundTheme, onKeyboard)
            };
            _model = DataContext as DowntimeDialogViewModel;
            _visibox_event = is_process_visibox_event;
            if (_model == null)
                return;

            // Update heading incase of break / lunch button clicked
            if (is_break_lunch)
            {
                _model.Heading = "Break / Lunch Reason";
                _model.Label = "Select the break / lunch reason";
                _model.IsBreakLunch = true;
                
            }
            if (false && _model.ReasonCodes.First() != null // ALWAYS HIDE PROGRESS BAR FOR NOW
                && _model.ReasonCodes.First().Text == "Load / Unload"
                && is_process_visibox_event)
            {
                gridProgessBar.Visibility = Visibility.Visible;
                var worker = new BackgroundWorker();
                worker.WorkerReportsProgress = true;
                worker.DoWork += worker_DoWork;
                worker.ProgressChanged += worker_ProgressChanged;
                worker.RunWorkerAsync();
            }
            else
            {
                gridProgessBar.Visibility = Visibility.Collapsed;
            }
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            int interval = _model.TotalSecondsProgressBar*10;
            
            for (int i = 1; i <= 100; i++)
            {
                (sender as BackgroundWorker).ReportProgress(i);
                Thread.Sleep(interval);
            }

            _timer = new System.Timers.Timer(1000) {Enabled = true};
            _timer.Elapsed += timer_Elapsed;
        }

        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            _progress_bar_value--;
            _progress_bar_text.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() =>
            {
                _progress_bar_text.Text = IntToTimeFormat(_progress_bar_value);
            }));
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            Brush foreground, background;
            _model.alarmColors(e.ProgressPercentage, out foreground, out background);

            _progress_bar_status.Foreground = background;
            _progress_bar_text.Foreground = foreground;
            _progress_bar_status.Value = e.ProgressPercentage;

            _progress_bar_value = (100 - e.ProgressPercentage) * _model.TotalSecondsProgressBar / 100;

            _progress_bar_text.Text = IntToTimeFormat(_progress_bar_value);
        }

        private string IntToTimeFormat(int seconds)
        {
            var s = Math.Abs(seconds);
            var text = string.Format("{0:00}:{1:00}", s/60, s%60);
            if (seconds < 0)
                text = "-" + text;
            return text;
        }

        private void VisiDialog_Loaded(object sender, RoutedEventArgs e)
        {

        }

        public ReasonCodeEntity SelectedReasonCode
        {
            get
            {
                ReasonCodeEntity val = null;
                SimpleNode node = (SimpleNode)_reason_codes.ActiveDataItem;
                if (node != null && node.Object != null)
                    val = (ReasonCodeEntity)node.Object;
                return val;
            }
        }

        public bool IsVisiBoxEvent
        {
            get { return _visibox_event; } 
        }

        public int? OperatorId
        {
            get
            {
                return _model.Operator != null ? _model.Operator.OperatorId : (int?)null;
            }
        }

        private void onKeyboard()
        {
            RaiseInputKeyboardClick();
        }

        private void onOK()
        {
            if (!_operator_id.IsEnabled || _model.validate())
            {
                Cancelled = false;
                if (_timer != null)
                    _timer.Enabled = false;
                close();
            }
        }

        private void onCancel()
        {
            Cancelled = true;
            if (_timer != null)
                _timer.Enabled = false;
            close();
        }
        
        public override void refresh()
        {
            ((DowntimeDialogViewModel)DataContext).refresh();
        }

        private void _reason_codes_SelectedNodesCollectionChanged(object sender, Infragistics.Controls.Menus.NodeSelectionEventArgs e)
        {
            var node = _reason_codes.SelectedDataItems.First() as SimpleNode;
            bool enable_menu = false;
            bool enable_operator = false;
            ReasonCodeEntity rc = node != null ? node.Object as ReasonCodeEntity : null;
            _model.ValidationError = "";
            if (rc != null)
            {
                enable_menu = true;
                if (rc.ShopClockEvent == (short)ReasonCodeItem.ShopClockEventEnum.In && rc.Description != "Changeover")
                {
                    enable_operator = true;
                    _operator_id.Focus();
                }
            }

            _operator_id.IsEnabled = enable_operator;

            _menu.Icons[0].IsEnabled = enable_menu;
        }

    }
}
